package com.lazar.servlet;

import com.lazar.dao.StudentDao;
import com.lazar.model.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String birth = req.getParameter("birth");

        SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
        Date date = null;
        try {
            date = sf.parse(birth);
        } catch (ParseException e) {
            throw new ServletException(e.getMessage());
        }

        Student stu = new Student();

        stu.setName(new String(name.getBytes("ISO-8859-1"),"UTF-8"));
        stu.setSex(new String(sex.getBytes("ISO-8859-1"),"UTF-8"));
        stu.setBirth(date);

        stu.addStudent();

        resp.sendRedirect("/usermanage/list");
    }
}
